package org.dromara.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.dromara.business.domain.vo.UserLevelExperienceLogVo;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.UserCoinLogBo;
import org.dromara.business.domain.vo.UserCoinLogVo;
import org.dromara.business.domain.UserCoinLog;
import org.dromara.business.mapper.UserCoinLogMapper;
import org.dromara.business.service.IUserCoinLogService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用户硬币变动记录Service业务层处理
 *
 * @author Hao Tong Xue
 * @date 2025-04-03
 */
@RequiredArgsConstructor
@Service
public class UserCoinLogServiceImpl implements IUserCoinLogService {

    private final UserCoinLogMapper baseMapper;
    private final SysUserMapper sysUserMapper;

    /**
     * 查询用户硬币变动记录
     *
     * @param id 主键
     * @return 用户硬币变动记录
     */
    @Override
    public UserCoinLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户硬币变动记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户硬币变动记录分页列表
     */
    @Override
    public TableDataInfo<UserCoinLogVo> queryPageList(UserCoinLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserCoinLog> lqw = buildQueryWrapper(bo);
        Page<UserCoinLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<UserCoinLogVo> records = result.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            List<SysUser> sysUsers = sysUserMapper.selectByIds(records.stream().map(UserCoinLogVo::getUserId).toList());
            Map<Long, String> userNameMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
            records.forEach(record -> {
                record.setUserName(userNameMap.get(record.getUserId()));
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户硬币变动记录列表
     *
     * @param bo 查询条件
     * @return 用户硬币变动记录列表
     */
    @Override
    public List<UserCoinLogVo> queryList(UserCoinLogBo bo) {
        LambdaQueryWrapper<UserCoinLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserCoinLog> buildQueryWrapper(UserCoinLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserCoinLog> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(UserCoinLog::getId);
        lqw.eq(bo.getUserId() != null, UserCoinLog::getUserId, bo.getUserId());
        lqw.eq(bo.getChangeAmount() != null, UserCoinLog::getChangeAmount, bo.getChangeAmount());
        lqw.eq(bo.getChangeType() != null, UserCoinLog::getChangeType, bo.getChangeType());
        if (StrUtil.isNotBlank(bo.getUserName())) {

            List<SysUser> sysUsers = sysUserMapper.selectList(Wrappers.<SysUser>lambdaQuery().likeRight(SysUser::getUserName, bo.getUserName()));
            if (CollUtil.isNotEmpty(sysUsers)) {
                lqw.in(UserCoinLog::getUserId, sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList()));
            }else {
                lqw.eq(UserCoinLog::getId, -1);
            }
        }
        lqw.ge(bo.getCreateTime() != null, UserCoinLog::getCreateTime, bo.getCreateTime());
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户硬币变动记录
     *
     * @param bo 用户硬币变动记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserCoinLogBo bo) {
        UserCoinLog add = MapstructUtils.convert(bo, UserCoinLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户硬币变动记录
     *
     * @param bo 用户硬币变动记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserCoinLogBo bo) {
        UserCoinLog update = MapstructUtils.convert(bo, UserCoinLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserCoinLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户硬币变动记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
